#include "widget.h"
#include "ui_widget.h"

#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>
#include <QShortcut>
#include <QTextEdit>
#include <QTextStream>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setLayout(ui->verticalLayout);
    connect(ui->openBtn,SIGNAL(pressed()),this,SLOT(openBtn_on_pressed()));
    connect(ui->safeBtn,SIGNAL(clicked()),this,SLOT(safeBtn_on_clicked()));
    connect(ui->comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(oncurrentIndexChanged(int)));
    connect(ui->textEdit,SIGNAL(cursorPositionChanged()),this,SLOT(on_cursorPositionChanged()));
    
    QShortcut *shortcutOpen = new QShortcut(QKeySequence(tr("Ctrl+O", "File|Open")),this);
    QShortcut *shortcutSave = new QShortcut(QKeySequence(tr("Ctrl+S", "File|Save")),this);
    QShortcut *shortcutClose = new QShortcut(QKeySequence(tr("Ctrl+W","File|Close")),this);
    QShortcut *shortcutZoomIn = new QShortcut(QKeySequence(tr("Ctrl+Shift+=","Fond|Big")),this);

    connect(shortcutOpen,&QShortcut::activated,[&](){
        openBtn_on_pressed();
    });
    connect(shortcutSave,&QShortcut::activated,[&](){
        safeBtn_on_clicked();
    });
    connect(shortcutClose,&QShortcut::activated,[&](){
        on_closeBtn_clicked();
    });

    connect(shortcutZoomIn,SIGNAL(activated()),this,SLOT(ZoonIn()));
    
}

Widget::~Widget()
{
    delete ui;
}

void Widget::openBtn_on_pressed()
{
    QString fileName = QFileDialog::getOpenFileName(this,tr("Open File"), "D:/qt_project", tr("Text Files (*.txt)"));
    file.setFileName(fileName);
    if(!file.open(QIODevice::ReadWrite|QIODevice::Text))
    {
        qDebug()<<"Error"<<file.errorString();
        return;
    }
    this->setWindowTitle(fileName+" -diy记事本");
    ui->textEdit->clear();
    QTextStream in(&file);
    // 获取编码格式
    const char* codingName =  ui->comboBox->currentText().toStdString().c_str();
    in.setCodec(codingName);
    while(!in.atEnd())
    {
        QString context = in.readLine();
        ui->textEdit->append(context);
    }
}

void Widget::safeBtn_on_clicked()
{
    if(!file.isOpen())
    {
        QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),"D:/qt_project/untitled.txt",tr("Text files (*.txt)"));
        file.setFileName(fileName);
        if(!file.open(QIODevice::WriteOnly|QIODevice::Text))
        {
            qDebug()<<"Error"<<file.errorString();
            return;
        }
        this->setWindowTitle(fileName+" -diy记事本");
    }
    file.close();
    if(!file.open(QIODevice::WriteOnly|QIODevice::Text|QIODevice::Truncate))
    {
        qDebug()<<"Error"<<file.errorString();
        return;
    }
    QTextStream out(&file);
    const char* codingName = ui->comboBox->currentText().toStdString().c_str();
    out.setCodec(codingName);
    QString context = ui->textEdit->toPlainText();
    out<<context;
}


void Widget::on_closeBtn_clicked()
{
    if(file.isOpen())
    {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText(tr("文件还没有保存\n""请问是否需要保存?"));
        QPushButton *saveButton = msgBox.addButton(tr("保存"), QMessageBox::YesRole);
        msgBox.addButton(tr("不保存"),QMessageBox::NoRole);
        msgBox.addButton(tr("取消"),QMessageBox::RejectRole);
        msgBox.setDefaultButton(saveButton);
        int ret = msgBox.exec();
        switch(ret)
        {
        case 0:// 保存
            safeBtn_on_clicked();
            ui->textEdit->clear();
            this->setWindowTitle("diy记事本");
            file.close();
            break;
        case 1: // 不保存
            ui->textEdit->clear();
            this->setWindowTitle("diy记事本");
            file.close();
            break;
        case 2:
            break;
        }

    }
}

void Widget::oncurrentIndexChanged(int index)
{
    ui->textEdit->clear();
    if(file.isOpen())
    {
        QTextStream in(&file);
        // 获取编码格式
        const char* codingName =  ui->comboBox->currentText().toStdString().c_str();
        in.setCodec(codingName);
        file.seek(0);
        while(!in.atEnd())
        {
            QString context = in.readLine();
            ui->textEdit->append(context);
        }
    }
}

void Widget::on_cursorPositionChanged()
{
    QTextCursor cursor = ui->textEdit->textCursor();
    //    qDebug() << cursor.blockNumber()+1<< " , " <<cursor.columnNumber()+1;
    const QString conText = "第"+QString::number(cursor.blockNumber()+1)+"行"+" 第"+QString::number(cursor.columnNumber())+"列\t|";
    ui->NumLable->setText(conText);

    // 设置
    QList<QTextEdit::ExtraSelection> extraSelection;
    QTextEdit::ExtraSelection ext;
    QBrush qbrush(Qt::lightGray);

    ext.cursor = ui->textEdit->textCursor();
    ext.format.setBackground(qbrush);
    ext.format.setProperty(QTextFormat::FullWidthSelection,true);

    extraSelection.append(ext);
    ui->textEdit->setExtraSelections(extraSelection);

}

void Widget::ZoonIn()
{
    QFont font = ui->textEdit->font();
    int fontSize = font.pointSize();
    if(fontSize == -1)
        return;
    int newFontSize = fontSize +1;
    font.setPointSize(newFontSize);
    ui->textEdit->setFont(font);
}


